package org.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.reggie.common.CustomException;
import org.example.reggie.dto.SetmealDto;
import org.example.reggie.entity.SetmealDish;
import org.example.reggie.service.SetMealDishService;
import org.example.reggie.service.SetMealService;
import org.example.reggie.entity.Setmeal;
import org.example.reggie.mapper.SetMealMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetMealService {

    @Autowired
    private SetMealDishService setMealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        dishes = dishes.stream().map(item -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setMealDishService.saveBatch(dishes);
    }

    @Override
    @Transactional
    public void deleteWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> lq = new LambdaQueryWrapper<>();
        lq.in(Setmeal::getId, ids);
        lq.eq(Setmeal::getStatus, 1);
        int count = this.count(lq);
        if(count > 0) {
            // 存在在售的套餐，不能删除
            throw new CustomException("存在在售的套餐，不能删除");
        }
        //删除setmeal表中的数据
        this.removeByIds(ids);

        //删除setmeal_dish表中的数据
        LambdaQueryWrapper<SetmealDish> lq1 = new LambdaQueryWrapper<>();
        lq1.in(SetmealDish::getSetmealId, ids);
        setMealDishService.remove(lq1);
    }
}
